<?php

namespace App\Kuafu\CustomPayment\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfSplitRelation;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\CustomPayment\Enum\CustomPaymentEnum;
use App\Kuafu\User\Model\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Cache;

class CustomPaymentModel extends BaseModel
{
    use KfSoftDeletes, KfSplitRelation, KfUid;

    protected $connection = 'mysql';
    protected $table      = 'custom_payments';
    protected $primaryKey = 'id';
    protected $fillable   = [
        'name',
        'reckonType',
        'isInvoice',
        'type',
        'createdByUid',
        'updatedByUid',
    ];
    protected $hidden     = [];


    public function createdByUidRel()
    {
        return $this->hasOne(User::class, 'id', 'createdByUid')->select('id', 'username');
    }

    public function updatedByUidRel()
    {
        return $this->hasOne(User::class, 'id', 'updatedByUid')->select(['id', 'username']);
    }

    /**
     * 关联下发门店
     *
     * @return HasMany
     */
    public function customPaymentShopRel(): HasMany
    {
        return $this->hasMany(CustomPaymentShopMappingsModel::class, 'payId', 'id');
    }

    /**
     * 新增
     * @param $data
     * @return Builder|\Illuminate\Database\Eloquent\Model
     */
    public static function add($data)
    {
        return self::query()->create($data);
    }

    /**
     * 支付列表
     *
     * @param $name
     * @param $status
     * @return array|Builder[]|Collection
     */
    public static function getList($name, $status)
    {
        return self::query()
                   ->with('createdByUidRel')
                   ->with('updatedByUidRel')
                   ->when(!empty($name), function ($query) use ($name) {
                       $query->where('name', 'like', "%{$name}%");
                   })
                   ->when(strlen($status), function ($query) use ($status) {
                       switch ($status) {
                           case CustomPaymentEnum::STATUS_ON:
                           case CustomPaymentEnum::STATUS_OFF:
                               $query->where('status', $status);
                               break;
                       }

                   })
                   ->orderBy('id', 'desc')
                   ->get();
    }

    public static function getNameById(int $id): string
    {
        return Cache::store('array')->remember('custom_payment_name:' . $id, 120, function () use ($id) {
            return (string)self::query()->where('id', $id)->value('name');
        });
    }

}
